'use strict'

const _ = require('lodash')
const Promise = require('bluebird')
const AV = require('leanengine')
const utils = require('../libs/utils')

const getBigTeam = function (ret) {
  var promises = ret.map(el => {
    var singles = el.relation('singles').query()
    var doubles = el.relation('doubles').query()
    var players = el.relation('players').query()
    singles.select('objectId', 'sex')
    doubles.select('objectId', 'discipline')
    return [singles.find(), doubles.find(), players.find()]
  })
  return Promise.all(_.flatten(promises))
  .then(ret2 => {
    var bigTeams = _.chunk(ret2, 3).map((el, index) => {
      return {
        playersByDisciplines: {
          ms: el[0].filter(x => x.get('sex') === 1).map(el => el.id),
          ws: el[0].filter(x => x.get('sex') === 2).map(el => el.id),
          md: el[1].filter(x => x.get('discipline') === 'md').map(el => el.id),
          wd: el[1].filter(x => x.get('discipline') === 'wd').map(el => el.id),
          xd: el[1].filter(x => x.get('discipline') === 'xd').map(el => el.id),
        },
        players: el[2].map(el => el.id),
        name: ret[index].get('name'),
        creator: ret[index].get('creator').id,
        objectId: ret[index].id
      }
    })
    return Promise.resolve(bigTeams)
  })
}

const func = {

  create (req) {
    const name = req.params.name

    var bigTeams = new AV.Object('BigTeams')
    return bigTeams.save({
      name,
      creator: req.user
    })
  },

  getMyBigTeams (req) {
    var query1 = new AV.Query('BigTeams').equalTo('players', req.user)
    var query2 = new AV.Query('BigTeams').equalTo('creator', req.user)
    return AV.Query.or(query1, query2)
    .find()
    .then(ret => {
      return getBigTeam(ret)
    })
  },

  getBigTeamsByIds (req) {
    const bigTeamsObjIds = req.params.bigTeamsObjIds

    var promises = bigTeamsObjIds.map(el => {
      return new AV.Query('BigTeams').get(el)
    })
    return Promise.all(promises)
    .then(ret => {
      return getBigTeam(ret)
    })
  }


}

AV.Cloud.define('bigTeams', function (req, res) {
  var promise
  if (!req.user) {
    promise = Promise.reject({
      msg: 'not loged in'
    })
  } else {
    promise = func[req.params.method](req)
  }
  return promise.then(function (ret) {
    res.success(ret)
  }).catch(function (err) {
    console.log(err)
    res.error(err)
  })
})
